package cn.qu.dockman.mgr.ws.exec;

import cn.qu.dockman.mgr.disparte.ArgDef;
import cn.qu.dockman.mgr.disparte.DispartMgr;
import cn.qu.dockman.mgr.entity.Container;
import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.service.ContainerService;
import cn.qu.dockman.mgr.service.HostService;
import cn.qu.dockman.protocol.command.Command;
import cn.qu.dockman.protocol.command.client.ContainerListCommand;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.qu.dockman.protocol.command.client.ContainerListCommand.ContainerListBody;

/**
 * Created by zh on 17/3/17.
 */
public class ContainerListCommandParser extends CommandParser {

    private DispartMgr dispartMgr;
    private HostService hostService;
    private ContainerService containerService;

    @Override
    public void before() {
        this.dispartMgr = getApplicationContext().getBean(DispartMgr.class);
        this.hostService = getApplicationContext().getBean(HostService.class);
        this.containerService = getApplicationContext().getBean(ContainerService.class);
    }

    @Override
    public void parse(Command command) {

        ContainerListCommand cmd = (ContainerListCommand) command;

        Host host = hostService.findByIp(this.getHost());

        if(host == null) return;

        List<Container> containerList = containerService.findByHostId(host.getId());

        Map<String, Container> containerMap = new HashMap<>();
        containerList.forEach(container -> containerMap.put(container.getContainerId(), container));

        ContainerListBody[] bodys = cmd.getBody();

        for (ContainerListBody body : bodys) {
            if (containerMap.containsKey(body.getId())) {
                containerMap.remove(body.getId());
            }
            ArgDef def = new ArgDef(ContainerListCommand.NAME, this.getHost(), this.getPort(),this.getHostname());
            def.setData(body);

            dispartMgr.notifyObservers(def);
        }
        containerMap.forEach((key, value) -> containerService.delete(value));

    }
}
